/**
 * 
 */
package com.lbt.weixin.server.controller;

import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lbt.framework.exception.MyException;
import com.lbt.framework.jackson.result.StatusResult;
import com.lbt.weixin.common.bean.entity.Car;
import com.lbt.weixin.common.bean.entity.User;
import com.lbt.weixin.common.service.UserService;

/**
 * Controller 基类
 * @author Moyq5
 * @date 2016年9月19日
 */
public class BaseController {

	@Resource
	UserService userService;
	
	protected long checkLogin(HttpServletRequest request) throws MyException {
		Object userIdObj =  request.getSession().getAttribute("userId");// 1;//
		if (null == userIdObj) {
			throw new MyException(0, "not login");// 未登录
		}
		long userId = Long.parseLong(String.valueOf(userIdObj));
		return userId;
	}
	
	protected long checkBind(HttpServletRequest request) throws MyException {
		long userId = checkLogin(request);
		getCarNo(request);
		return userId;
	}
	
	protected String getCarNo(HttpServletRequest request) throws MyException {
		long userId = checkLogin(request);;
		Object carNo = request.getSession().getAttribute("carNo");//"闽DQK590";//闽DV1821 
		if (null == carNo) {
			User user = userService.one(userId);
			Set<Car> cars = user.getCars();
			if (null == cars || cars.size() == 0) {
				throw new MyException(0, "not bind");// 未绑定
			}
			Car car = cars.iterator().next();
			carNo = car.getCarNo();
			request.getSession().setAttribute("carNo", carNo);
			request.getSession().setAttribute("carId", car.getCarId());
		}
		return String.valueOf(carNo);
	}
	
	@ExceptionHandler({MyException.class})
    @ResponseBody
    public StatusResult handleBindException(MyException ex)
    {
        StatusResult jsonResult = new StatusResult();
        jsonResult.setCode("" + ex.getCode());
        jsonResult.setMessage(ex.getMessage());
        return jsonResult;
    }
    
}
